package com.module.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.module.framework.constants.SystemConstants;
import com.module.framework.domain.Order;
import com.module.framework.domain.OrderItem;
import com.module.framework.domain.Product;
import com.module.framework.mapper.OrderItemMapper;
import com.module.framework.mapper.OrderMapper;
import com.module.framework.mapper.ProductMapper;
import com.module.framework.service.OrderService;
import com.module.framework.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lexang
 * @since 2022-03-04
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {


    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ProductMapper productMapper;


    @Override
    public PageVO orderList(Integer pageNum, Integer pageSize,Integer userId) {
        PageVO pageVO;
        LambdaQueryWrapper<Order> queryWrapper = Wrappers.<Order>lambdaQuery()
                .eq(Order::getUserId, userId)
                .eq(Order::getDelFlag, 0);
        if (pageNum == null && pageSize == null) {
            List<Order> lists = this.list(queryWrapper);
            pageVO = new PageVO(lists, lists.size());
        } else {
            pageSize = pageSize == null ? SystemConstants.PAGE_SIZE : pageSize;
            Page<Order> page = new Page<>(pageNum, pageSize);
            this.page(page, queryWrapper);
            // 查询categoryName
            List<Order> records = page.getRecords();
            pageVO = new PageVO(records, (int) page.getTotal());
        }
        return pageVO;
    }

    @Override
    public List<Product> orderProductList(Integer orderId) {
        List<OrderItem> orderItems = orderItemMapper.selectList(Wrappers.<OrderItem>lambdaQuery()
                .eq(OrderItem::getOid, orderId).select(OrderItem::getPid)
                .eq(OrderItem::getDelFlag,0));
        List<Product> products = productMapper.selectBatchIds(orderItems.stream().map(OrderItem::getPid).collect(Collectors.toList()));
        return products;
    }
}
